/**
 * IndexedDB测试工具
 * 用于快速测试数据库功能
 */

import { dbManager, ChatRecord, ChatMessage, LigHistoryRecord } from './indexedDB';

class DBTester {
    /**
     * 运行测试流程
     */
    async runTests() {
        console.log('开始测试IndexedDB功能...');
        try {
            await this.testInit();

            // 测试聊天记录功能
            console.log('\n===== 测试聊天记录功能 =====');
            await this.testAddChat();
            await this.testGetChat();
            await this.testAddMessage();
            await this.testUpdateChat();
            await this.testGetAllChats();
            await this.testDeleteChat();

            // 测试LigHistory功能
            console.log('\n===== 测试LigHistory功能 =====');
            await this.testAddLigHistory();
            await this.testGetLigHistory();
            await this.testUpdateLigHistory();
            await this.testAddLigHistoryBatch();
            await this.testGetAllLigHistory();
            await this.testClearAllLigHistory();

            console.log('\n测试完成，所有功能正常✅');
        } catch (error) {
            console.error('测试失败:', error);
        } finally {
            dbManager.closeDB();
        }
    }

    /**
     * 测试数据库初始化
     */
    private async testInit() {
        console.log('测试数据库初始化...');
        const result = await dbManager.initDB();
        console.assert(result === true, '数据库初始化失败');
        console.log('数据库初始化成功✅');
    }

    /**
     * 测试添加聊天记录
     */
    private async testAddChat() {
        console.log('测试添加聊天记录...');
        const testChat: ChatRecord = {
            chatId: `test-${Date.now()}`,
            messages: [],
            model: 'test-model',
            title: '测试聊天',
            desc: '这是一个测试聊天记录'
        };

        const result = await dbManager.addChat(testChat);
        console.assert(result === true, '添加聊天记录失败');
        console.log('添加聊天记录成功✅');

        // 保存测试数据的ID以供后续测试使用
        this.testChatId = testChat.chatId;
    }

    /**
     * 测试获取聊天记录
     */
    private async testGetChat() {
        console.log('测试获取聊天记录...');
        const chat = await dbManager.getChat(this.testChatId);
        console.assert(chat !== null, '获取聊天记录失败');
        console.assert(chat?.chatId === this.testChatId, '获取的聊天记录ID不匹配');
        console.log('获取聊天记录成功✅');
    }

    /**
     * 测试添加消息
     */
    private async testAddMessage() {
        console.log('测试添加消息...');

        const userMessage: ChatMessage = {
            role: 'user',
            content: '这是一条测试消息',
            timestamp: Date.now()
        };

        const result = await dbManager.addMessageToChat(this.testChatId, userMessage);
        console.assert(result === true, '添加消息失败');

        // 验证消息是否添加成功
        const chat = await dbManager.getChat(this.testChatId);
        console.assert(chat?.messages.length === 1, '消息数量不正确');
        console.assert(chat?.messages[0].content === userMessage.content, '消息内容不匹配');

        console.log('添加消息成功✅');
    }

    /**
     * 测试更新聊天记录
     */
    private async testUpdateChat() {
        console.log('测试更新聊天记录...');

        const chat = await dbManager.getChat(this.testChatId);
        if (!chat) {
            throw new Error('未找到测试聊天记录');
        }

        // 更新标题
        const newTitle = '已更新的测试聊天';
        chat.title = newTitle;

        const result = await dbManager.updateChat(chat);
        console.assert(result === true, '更新聊天记录失败');

        // 验证更新是否成功
        const updatedChat = await dbManager.getChat(this.testChatId);
        console.assert(updatedChat?.title === newTitle, '聊天记录标题未更新');

        console.log('更新聊天记录成功✅');
    }

    /**
     * 测试获取所有聊天记录
     */
    private async testGetAllChats() {
        console.log('测试获取所有聊天记录...');

        const chats = await dbManager.getAllChats();
        console.assert(Array.isArray(chats), '返回结果不是数组');
        console.assert(chats.length > 0, '返回的聊天记录为空');
        console.assert(chats.some(chat => chat.chatId === this.testChatId), '返回结果中没有测试聊天记录');

        console.log(`获取所有聊天记录成功，共${chats.length}条✅`);
    }

    /**
     * 测试删除聊天记录
     */
    private async testDeleteChat() {
        console.log('测试删除聊天记录...');

        const result = await dbManager.deleteChat(this.testChatId);
        console.assert(result === true, '删除聊天记录失败');

        // 验证删除是否成功
        const chat = await dbManager.getChat(this.testChatId);
        console.assert(chat === null, '聊天记录未被删除');

        console.log('删除聊天记录成功✅');
    }

    /**
     * 测试添加LigHistory记录
     */
    private async testAddLigHistory() {
        console.log('测试添加LigHistory记录...');

        const testRecord: LigHistoryRecord = {
            id: this.testLigHistoryId,
            name: '测试LigHistory记录'
        };

        const result = await dbManager.addLigHistory(testRecord);
        console.assert(result === true, '添加LigHistory记录失败');

        console.log('添加LigHistory记录成功✅');
    }

    /**
     * 测试获取LigHistory记录
     */
    private async testGetLigHistory() {
        console.log('测试获取LigHistory记录...');

        const record = await dbManager.getLigHistory(this.testLigHistoryId);
        console.assert(record !== null, '获取LigHistory记录失败');
        console.assert(record?.id === this.testLigHistoryId, '获取的LigHistory记录ID不匹配');
        console.assert(record?.name === '测试LigHistory记录', '获取的LigHistory记录名称不匹配');

        console.log('获取LigHistory记录成功✅');
    }

    /**
     * 测试更新LigHistory记录
     */
    private async testUpdateLigHistory() {
        console.log('测试更新LigHistory记录...');

        const record = await dbManager.getLigHistory(this.testLigHistoryId);
        if (!record) {
            throw new Error('未找到测试LigHistory记录');
        }

        // 更新名称
        const newName = '已更新的LigHistory记录';
        record.name = newName;

        const result = await dbManager.updateLigHistory(record);
        console.assert(result === true, '更新LigHistory记录失败');

        // 验证更新是否成功
        const updatedRecord = await dbManager.getLigHistory(this.testLigHistoryId);
        console.assert(updatedRecord?.name === newName, 'LigHistory记录名称未更新');

        console.log('更新LigHistory记录成功✅');
    }

    /**
     * 测试批量添加LigHistory记录
     */
    private async testAddLigHistoryBatch() {
        console.log('测试批量添加LigHistory记录...');

        const batchRecords: LigHistoryRecord[] = [
            { id: this.testLigHistoryId + 1, name: '批量测试记录1' },
            { id: this.testLigHistoryId + 2, name: '批量测试记录2' },
            { id: this.testLigHistoryId + 3, name: '批量测试记录3' }
        ];

        const result = await dbManager.addLigHistoryBatch(batchRecords);
        console.assert(result === true, '批量添加LigHistory记录失败');

        // 验证添加是否成功
        const record1 = await dbManager.getLigHistory(this.testLigHistoryId + 1);
        const record2 = await dbManager.getLigHistory(this.testLigHistoryId + 2);
        const record3 = await dbManager.getLigHistory(this.testLigHistoryId + 3);

        console.assert(record1 !== null && record2 !== null && record3 !== null, '批量添加的记录获取失败');

        console.log('批量添加LigHistory记录成功✅');
    }

    /**
     * 测试获取所有LigHistory记录
     */
    private async testGetAllLigHistory() {
        console.log('测试获取所有LigHistory记录...');

        const records = await dbManager.getAllLigHistory();
        console.assert(Array.isArray(records), '返回结果不是数组');
        console.assert(records.length >= 4, '返回的LigHistory记录数量不正确');
        console.assert(records.some(record => record.id === this.testLigHistoryId), '返回结果中没有测试LigHistory记录');

        console.log(`获取所有LigHistory记录成功，共${records.length}条✅`);
    }

    /**
     * 测试清空所有LigHistory记录
     */
    private async testClearAllLigHistory() {
        console.log('测试清空所有LigHistory记录...');

        const result = await dbManager.clearAllLigHistory();
        console.assert(result === true, '清空所有LigHistory记录失败');

        // 验证清空是否成功
        const records = await dbManager.getAllLigHistory();
        console.assert(records.length === 0, 'LigHistory记录未被清空');

        console.log('清空所有LigHistory记录成功✅');
    }

    private testChatId: string = '';
    private testLigHistoryId: number = Date.now();
}

// 导出测试工具实例
export const dbTester = new DBTester(); 